import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.pages.base_page import BasePage
from core.utils.i18n import t
from ui.styles.theme import Theme

class RegisterPage(BasePage):
    def create_widgets(self):
        # 获取主题颜色
        fg_primary = Theme.get_color('fg_primary')
        fg_tertiary = Theme.get_color('fg_tertiary')
        accent_color = Theme.get_color('accent')
        
        # 主容器 - 居中显示
        main_container = customtkinter.CTkFrame(self, fg_color="transparent")
        main_container.place(relx=0.5, rely=0.5, anchor="center")
        
        # 标题
        title_label = customtkinter.CTkLabel(
            main_container, 
            text="Create Account",
            font=("Arial", 24, "bold"),
            text_color=fg_primary,
            bg_color="transparent"
        )
        title_label.pack(pady=10)
        
        subtitle_label = customtkinter.CTkLabel(
            main_container,
            text="Join Ali Bao Bao today", 
            font=("Arial", 12),
            text_color=fg_tertiary,
            bg_color="transparent"
        )
        subtitle_label.pack(pady=5)
        
        # 注册表单容器
        register_frame = customtkinter.CTkFrame(main_container, fg_color=("gray95", "gray20"))
        register_frame.pack(pady=20, padx=50, fill="x", ipadx=20, ipady=20)
        
        # 用户名输入
        username_label = customtkinter.CTkLabel(register_frame, text="Username:*", font=("Arial", 12))
        username_label.grid(row=0, column=0, padx=5, pady=10, sticky="e")
        
        self.username_entry = customtkinter.CTkEntry(
            register_frame, 
            width=250,
            height=35,
            font=("Arial", 12)
        )
        self.username_entry.grid(row=0, column=1, padx=5, pady=10, sticky="w")
        self.username_entry.focus()
        
        # 邮箱输入
        email_label = customtkinter.CTkLabel(register_frame, text="Email:*", font=("Arial", 12))
        email_label.grid(row=1, column=0, padx=5, pady=10, sticky="e")
        
        self.email_entry = customtkinter.CTkEntry(
            register_frame, 
            width=250,
            height=35,
            font=("Arial", 12)
        )
        self.email_entry.grid(row=1, column=1, padx=5, pady=10, sticky="w")
        
        # 密码输入
        password_label = customtkinter.CTkLabel(register_frame, text="Password:*", font=("Arial", 12))
        password_label.grid(row=2, column=0, padx=5, pady=10, sticky="e")
        
        # 密码输入框和可视化切换按钮
        password_frame = customtkinter.CTkFrame(register_frame, fg_color="transparent")
        password_frame.grid(row=2, column=1, padx=5, pady=10, sticky="w")
        
        self.password_entry = customtkinter.CTkEntry(
            password_frame, 
            width=220,
            height=35,
            show="•", 
            font=("Arial", 12)
        )
        self.password_entry.pack(side="left")
        
        self.password_visible = False
        self.password_toggle_btn = customtkinter.CTkButton(
            password_frame, 
            text="👁", 
            width=35,
            height=35,
            font=("Arial", 12),
            command=self.toggle_password_visibility,
            fg_color="transparent",
            hover_color=("gray80", "gray30")
        )
        self.password_toggle_btn.pack(side="left", padx=5)
        
        # 密码强度显示
        self.password_strength_label = customtkinter.CTkLabel(
            register_frame,
            text="强度: 无",
            font=("Arial", 10, "bold"),
            text_color=fg_tertiary
        )
        self.password_strength_label.grid(row=2, column=2, padx=5, pady=10, sticky="w")
        
        # 绑定密码输入事件
        self.password_entry.bind('<KeyRelease>', self.update_password_strength)
        
        # 确认密码
        confirm_password_label = customtkinter.CTkLabel(register_frame, text="Confirm Password:*", font=("Arial", 12))
        confirm_password_label.grid(row=3, column=0, padx=5, pady=10, sticky="e")
        
        # 确认密码输入框和可视化切换按钮
        confirm_password_frame = customtkinter.CTkFrame(register_frame, fg_color="transparent")
        confirm_password_frame.grid(row=3, column=1, padx=5, pady=10, sticky="w")
        
        self.confirm_password_entry = customtkinter.CTkEntry(
            confirm_password_frame, 
            width=220,
            height=35,
            show="•", 
            font=("Arial", 12)
        )
        self.confirm_password_entry.pack(side="left")
        
        self.confirm_password_visible = False
        self.confirm_password_toggle_btn = customtkinter.CTkButton(
            confirm_password_frame,
            text="👁",
            width=35,
            height=35,
            font=("Arial", 12),
            command=self.toggle_confirm_password_visibility,
            fg_color="transparent",
            hover_color=("gray80", "gray30")
        )
        self.confirm_password_toggle_btn.pack(side="left", padx=5)
        
        # 用户类型选择
        user_type_label = customtkinter.CTkLabel(register_frame, text="Account Type:*", font=("Arial", 12))
        user_type_label.grid(row=4, column=0, padx=5, pady=10, sticky="e")
        
        self.user_type = tk.StringVar(value="customer")
        user_type_frame = customtkinter.CTkFrame(register_frame, fg_color="transparent")
        user_type_frame.grid(row=4, column=1, padx=5, pady=10, sticky="w")
        
        customer_radio = customtkinter.CTkRadioButton(
            user_type_frame, 
            text="Customer (Buyer)", 
            variable=self.user_type, 
            value="customer",
            font=("Arial", 11)
        )
        customer_radio.pack(anchor="w", pady=3)
        
        seller_radio = customtkinter.CTkRadioButton(
            user_type_frame, 
            text="Seller", 
            variable=self.user_type, 
            value="seller",
            font=("Arial", 11)
        )
        seller_radio.pack(anchor="w", pady=3)
        
        # 卖家店铺名（动态显示）
        self.store_name_frame = customtkinter.CTkFrame(register_frame, fg_color="transparent")
        self.store_name_label = customtkinter.CTkLabel(
            self.store_name_frame, 
            text="Store Name:*", 
            font=("Arial", 12)
        )
        self.store_name_label.grid(row=0, column=0, padx=5, pady=10, sticky="e")
        
        self.store_name_entry = customtkinter.CTkEntry(
            self.store_name_frame, 
            width=250,
            height=35,
            font=("Arial", 12)
        )
        self.store_name_entry.grid(row=0, column=1, padx=5, pady=10, sticky="w")
        
        # 绑定用户类型变化事件
        self.user_type.trace('w', self.on_user_type_changed)
        
        # 条款同意
        self.agree_terms = tk.BooleanVar()
        terms_check = customtkinter.CTkCheckBox(
            register_frame,
            text="I agree to the Terms of Service and Privacy Policy",
            variable=self.agree_terms,
            font=("Arial", 11)
        )
        terms_check.grid(row=5, column=0, columnspan=2, padx=5, pady=15, sticky="w")
        
        # 绑定回车键
        self.username_entry.bind('<Return>', lambda e: self.email_entry.focus())
        self.email_entry.bind('<Return>', lambda e: self.password_entry.focus())
        self.password_entry.bind('<Return>', lambda e: self.confirm_password_entry.focus())
        self.confirm_password_entry.bind('<Return>', lambda e: self.register())
        
        # 按钮框架
        button_frame = customtkinter.CTkFrame(register_frame, fg_color="transparent")
        button_frame.grid(row=6, column=0, columnspan=2, pady=10)
        
        # 注册按钮
        register_btn = customtkinter.CTkButton(
            button_frame, 
            text="Create Account", 
            command=self.register,
            width=150,
            height=40,
            font=("Arial", 14, "bold"),
            fg_color=accent_color,
            hover_color="#E55A2B",
            corner_radius=10
        )
        register_btn.grid(row=0, column=0, padx=10)
        
        # 返回按钮
        back_btn = customtkinter.CTkButton(
            button_frame, 
            text="Back to Login", 
            command=self.show_login,
            width=150,
            height=40,
            font=("Arial", 14),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=10
        )
        back_btn.grid(row=0, column=1, padx=10)
        
        # 底部链接
        bottom_frame = customtkinter.CTkFrame(main_container, fg_color="transparent")
        bottom_frame.pack(pady=10)
        
        customtkinter.CTkLabel(
            bottom_frame,
            text="Already have an account?",
            font=("Arial", 11),
            text_color=fg_tertiary
        ).pack(side="left")
        
        customtkinter.CTkButton(
            bottom_frame,
            text="Sign in here",
            command=self.show_login,
            fg_color="transparent",
            hover_color=("gray80", "gray30"),
            text_color=("blue", "lightblue"),
            font=("Arial", 11)
        ).pack(side="left", padx=5)
    
    def toggle_password_visibility(self):
        """切换密码可见性"""
        self.password_visible = not self.password_visible
        if self.password_visible:
            self.password_entry.configure(show="")
            self.password_toggle_btn.configure(text="🔒")
        else:
            self.password_entry.configure(show="•")
            self.password_toggle_btn.configure(text="👁")
    
    def toggle_confirm_password_visibility(self):
        """切换确认密码可见性"""
        self.confirm_password_visible = not self.confirm_password_visible
        if self.confirm_password_visible:
            self.confirm_password_entry.configure(show="")
            self.confirm_password_toggle_btn.configure(text="🔒")
        else:
            self.confirm_password_entry.configure(show="•")
            self.confirm_password_toggle_btn.configure(text="👁")
    
    def update_password_strength(self, event=None):
        """更新密码强度显示"""
        try:
            from core.models.user import User
            password = self.password_entry.get()
            strength_level, strength_text, color = User.calculate_password_strength(password)
            self.password_strength_label.configure(
                text=f"强度: {strength_text}",
                text_color=color
            )
        except Exception as e:
            from core.utils.logger import debug
            debug(f"Failed to update password strength: {e}")
    
    def on_user_type_changed(self, *args):
        """当用户类型改变时更新界面"""
        if self.user_type.get() == "seller":
            # 显示店铺名输入框
            self.store_name_frame.grid(row=5, column=0, columnspan=2, sticky="w", padx=5)
            # 自动生成店铺名
            username = self.username_entry.get().strip()
            if username and not self.store_name_entry.get():
                self.store_name_entry.delete(0, tk.END)
                self.store_name_entry.insert(0, f"{username}'s Store")
        else:
            # 隐藏店铺名输入框
            self.store_name_frame.grid_remove()
    
    def register(self):
        """处理注册逻辑"""
        # 获取输入值
        username = self.username_entry.get().strip()
        email = self.email_entry.get().strip()
        password = self.password_entry.get()
        confirm_password = self.confirm_password_entry.get()
        user_type = self.user_type.get()
        
        # 输入验证
        if not username or not email or not password:
            messagebox.showwarning("Input Error", "Please fill in all required fields")
            return
        
        if len(username) < 3:
            messagebox.showwarning("Input Error", "Username must be at least 3 characters")
            return
        
        if "@" not in email or "." not in email:
            messagebox.showwarning("Input Error", "Please enter a valid email address")
            return
        
        if password != confirm_password:
            messagebox.showwarning("Input Error", "Passwords do not match")
            self.password_entry.delete(0, tk.END)
            self.confirm_password_entry.delete(0, tk.END)
            self.password_entry.focus()
            return
        
        # 使用新的密码强度验证
        from core.models.user import User
        is_valid, error_msg = User.validate_password_strength(password)
        if not is_valid:
            messagebox.showwarning("Password Error", error_msg)
            return
        
        if not self.agree_terms.get():
            messagebox.showwarning("Input Error", "You must agree to the Terms of Service")
            return
        
        # 卖家特定验证
        if user_type == "seller":
            store_name = self.store_name_entry.get().strip()
            if not store_name:
                messagebox.showwarning("Input Error", "Store name is required for sellers")
                return
        
        try:
            # 准备额外参数
            extra_args = {}
            if user_type == "seller":
                extra_args['store_name'] = self.store_name_entry.get().strip()
            
            # 注册用户
            user = self.controller.auth_service.register(
                username, email, password, user_type, **extra_args
            )
            
            # 注册成功
            messagebox.showinfo(
                "Success", 
                f"Account created successfully!\n\n"
                f"Welcome to Ali Bao Bao, {username}!\n"
                f"Account type: {user_type.capitalize()}"
            )
            
            # 自动登录并跳转到商品页面
            self.controller.auth_service.current_user = user
            
            # 更新购物车用户ID
            self.controller.update_cart_user()
            
            self.controller.show_page("ProductPage")
            
        except Exception as e:
            # 注册失败
            messagebox.showerror("Registration Failed", str(e))
    
    def show_login(self):
        """跳转到登录页面"""
        self.controller.show_page("LoginPage")
    
    def update_data(self):
        """更新页面数据（如果需要）"""
        # 清空所有输入框
        self.username_entry.delete(0, tk.END)
        self.email_entry.delete(0, tk.END)
        self.password_entry.delete(0, tk.END)
        self.confirm_password_entry.delete(0, tk.END)
        self.store_name_entry.delete(0, tk.END)
        self.agree_terms.set(False)
        self.user_type.set("customer")
        self.on_user_type_changed()  # 更新界面状态
        
        # 重置密码强度显示
        fg_tertiary = Theme.get_color('fg_tertiary')
        self.password_strength_label.configure(text="强度: 无", text_color=fg_tertiary)
        
        # 重置密码可见性
        if self.password_visible:
            self.toggle_password_visibility()
        if self.confirm_password_visible:
            self.toggle_confirm_password_visibility()
        
        self.username_entry.focus()
